import ctypes
import winreg
import subprocess
import platform
from urllib import parse
import socket
import random
import time
import os
import psutil

def excmd(cmd):
    try:
        result = subprocess.check_output(cmd, text=True)
        # print(result.strip())
        res = parse.quote(result.strip()).replace("%00", "").replace("%0A", "").replace(
            "%E8%9A%AB%5CO%10b%E7%83%BA%E5%AD%BE%10b%020",
            "%E6%93%8D%E4%BD%9C%E6%88%90%E5%8A%9F%E5%AE%8C%E6%88%90%E3%80%82")
        return parse.unquote(res)
    except subprocess.CalledProcessError as e:
        res = parse.quote(e.output.strip()).replace("%00", "")
        return parse.unquote(res)


def sc_del_server(ServerName):
    return excmd("sc delete %s" % ServerName)


def sc_stop_server(ServerName):
    return excmd("sc stop %s" % ServerName)


def sc_check_server_status(ServerName):
    return excmd("sc stop %s" % (ServerName))


def sc_check_server_config(ServerName):
    return excmd("sc qc %s" % (ServerName))


def sc_start_server(ServerName):
    return excmd("sc start %s" % (ServerName))


def net_start_server(ServerName):
    return excmd("net start %s" % (ServerName))


def net_stop_server(ServerName):
    return excmd("net stop %s" % (ServerName))


def is_port_in_use(port):
    """检查特定端口是否被占用"""
    for conn in psutil.net_connections(kind='inet'):

        try:
            if conn.laddr.port == port:
                print(conn.laddr.port)
                return True
        except:
            pass
    return False

def get_new_port(start=1024, end=65535):
    port = random.randint(start, end)
    if not is_port_in_use(port):
        return port
    return get_new_port(start=start, end=end)


def sc_set_start_type(ServerName: str, startType: str = "auto"):
    '''
    设备服务启动类型
    :param ServerName: 服务名称
    :param startType: auto | demand | disabled
    :return:
    '''
    res = excmd("sc config %s start = %s" % (ServerName, startType))
    print("设备服务启动类型", res)
    return res


def is_mitmproxy_cert_installed():
    try:
        # 使用 PowerShell 检查证书是否存在
        res = subprocess.check_output(['powershell',
                                       'Get-ChildItem -Path Cert:\CurrentUser\Root | Where-Object {$_.Subject -like "*mitmproxy*"}'])
        if res:
            return True
        return False
    except subprocess.CalledProcessError as e:
        return False

def install_mitmproxy_certificate(cert_path):
    system_platform = platform.system()
    if system_platform == "Windows":
        # Windows系统下使用certutil命令
        try:
            res = subprocess.run(["certutil.exe", "-addstore", "root", cert_path], check=True, capture_output=True,
                                 text=True)
            print(res)
            print("Mitmproxy证书已成功安装到根证书存储中。")
        except subprocess.CalledProcessError as e:
            print(f"安装Mitmproxy证书失败: {e}")



# 检查文件或目录是否存在
def check_path_exists(path):
    return os.path.exists(path)

# 检查指定路径是否为文件并存在
def check_file_exists(file_path):
    return os.path.isfile(file_path) and os.path.exists(file_path)

def set_system_proxy(enable_proxy, proxy_address="http://127.0.0.1:8080"):
    try:
        # 代理服务器地址和端口
        proxy_server = proxy_address

        # 打开注册表键
        key_path = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)

        # 设置代理服务器
        if enable_proxy:
            winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, proxy_server)
            winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, 1)
        else:
            # 关闭代理
            winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, 0)

        # 刷新代理设置
        INTERNET_OPTION_REFRESH = 37
        INTERNET_OPTION_SETTINGS_CHANGED = 39
        internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
        internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
        internet_set_option(0, INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)

        # 关闭注册表键
        winreg.CloseKey(key)
        print("系统代理设置成功！")
    except Exception as e:
        print(f"设置系统代理失败: {e}")


if __name__ == "__main__":

    # status = sc_check_server_status("Redis50141")
    # print(status)
    # resp = excmd(r"D:\code\my-mitmproxy\Redis-x64-5.0.14.1\redis-server --service-install D:\code\my-mitmproxy\Redis-x64-5.0.14.1\redis.windows.conf --service-name Redis50141 --port 50141")
    # print(resp)

    # if is_mitmproxy_cert_installed():
    #     print("Mitmproxy证书已安装")
    # else:
    #     print("Mitmproxy证书未安装")
    #     "mitmproxy-ca-cert.p12"
    #     # 替换为实际的证书路径
    #     certificate_path = r"mitmproxy-ca-cert.cer"
    #     install_mitmproxy_certificate(certificate_path)
    #
    # # 设置代理（启用代理）
    # set_system_proxy(enable_proxy=True, proxy_address="http://127.0.0.1:8080")
    # # 设置代理（关闭代理）

    set_system_proxy(enable_proxy=False)
    # print("8080",is_port_in_use(8080))
    # t = time.time()
    # prot = get_new_port()
    # print(prot)
    # print(time.time() - t)
